// pages/common/article-detail/article-detail.ts
import { getArticleDetail } from '../../../api/article'

Page({
  data: {
    // 文章ID
    articleId: null,
    // 文章详情
    articleDetail: null,
    // 文章内容（处理后的HTML）
    articleContent: '',
    // 加载状态
    loading: false
  },

  onLoad(options) {
    console.log('文章详情页面加载完成', options)
    
    if (options.id) {
      this.setData({
        articleId: parseInt(options.id)
      })
      this.loadArticleDetail()
    } else {
      wx.showToast({
        title: '文章ID不存在',
        icon: 'none'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    }
  },

  onShow() {
    console.log('文章详情页面显示')
  },

  // 加载文章详情
  async loadArticleDetail() {
    if (!this.data.articleId) return

    this.setData({
      loading: true
    })

    try {
      const res = await getArticleDetail(this.data.articleId)
      
      if (res.status === 200 && res.data) {
        const articleDetail = res.data
        
        // 添加分类名称和处理图片数据
        articleDetail.categoryName = this.getCategoryName(articleDetail.cid)
        // 从image_input数组中取第一张图片作为封面图
        articleDetail.image = this.getFirstImage(articleDetail.image_input)
        
        // 处理HTML内容，确保图片样式正确
        const processedContent = this.processHtmlContent(articleDetail.content)
        
        this.setData({
          articleDetail,
          articleContent: processedContent,
          loading: false
        })

        // 设置页面标题
        wx.setNavigationBarTitle({
          title: articleDetail.title || '展会详情'
        })
      } else {
        throw new Error(res.msg || '文章不存在')
      }
    } catch (error) {
      console.error('加载文章详情失败:', error)
      this.setData({
        loading: false
      })
      wx.showToast({
        title: error.message || '加载失败',
        icon: 'none'
      })
      
      // 延迟返回上一页
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    }
  },

  // 获取分类名称
  getCategoryName(cid) {
    const categoryMap = {
      0: '热门',
      1: '模切材料',
      2: '模切加工'
    }
    return categoryMap[cid] || '其他'
  },

  // 从image_input数组中获取第一张图片
  getFirstImage(imageInput) {
    if (!imageInput || !Array.isArray(imageInput) || imageInput.length === 0) {
      return ''
    }
    return imageInput[0] || ''
  },

  // 处理HTML内容
  processHtmlContent(content) {
    if (!content) return ''
    
    // 处理图片样式，确保在小程序中正确显示
    let processedContent = content.replace(
      /<img([^>]*?)src="([^"]*?)"([^>]*?)>/gi,
      '<img$1src="$2"$3 style="max-width:100%;height:auto;border-radius:8rpx;margin:16rpx 0;">'
    )
    
    // 处理标题样式
    processedContent = processedContent.replace(
      /<h1([^>]*?)>/gi,
      '<h1$1 style="font-size:36rpx;font-weight:600;color:#1a1a1a;margin:32rpx 0 16rpx 0;padding-left:8rpx;border-left:8rpx solid #0052d9;">'
    )
    
    processedContent = processedContent.replace(
      /<h2([^>]*?)>/gi,
      '<h2$1 style="font-size:32rpx;font-weight:600;color:#1a1a1a;margin:32rpx 0 16rpx 0;">'
    )
    
    processedContent = processedContent.replace(
      /<h3([^>]*?)>/gi,
      '<h3$1 style="font-size:28rpx;font-weight:600;color:#1a1a1a;margin:32rpx 0 16rpx 0;">'
    )
    
    // 处理段落样式
    processedContent = processedContent.replace(
      /<p([^>]*?)>/gi,
      '<p$1 style="margin-bottom:16rpx;font-size:30rpx;line-height:1.8;color:#1a1a1a;">'
    )
    
    // 处理列表样式
    processedContent = processedContent.replace(
      /<ul([^>]*?)>/gi,
      '<ul$1 style="padding-left:40rpx;margin-bottom:16rpx;">'
    )
    
    processedContent = processedContent.replace(
      /<ol([^>]*?)>/gi,
      '<ol$1 style="padding-left:40rpx;margin-bottom:16rpx;">'
    )
    
    processedContent = processedContent.replace(
      /<li([^>]*?)>/gi,
      '<li$1 style="margin-bottom:8rpx;">'
    )
    
    // 处理引用样式
    processedContent = processedContent.replace(
      /<blockquote([^>]*?)>/gi,
      '<blockquote$1 style="background:#f8f9fc;border-left:8rpx solid #e37318;padding:24rpx 32rpx;margin:16rpx 0;font-style:italic;color:#4e5969;border-radius:0 8rpx 8rpx 0;">'
    )
    
    return processedContent
  },

  // 分享功能
  onShareAppMessage() {
    const articleDetail = this.data.articleDetail
    if (articleDetail) {
      return {
        title: articleDetail.title,
        path: `/pages/common/article-detail/article-detail?id=${this.data.articleId}`,
        imageUrl: articleDetail.image || ''
      }
    }
    return {
      title: '展会详情',
      path: '/pages/common/article-detail/article-detail'
    }
  },

  // 分享到朋友圈
  onShareTimeline() {
    const articleDetail = this.data.articleDetail
    if (articleDetail) {
      return {
        title: articleDetail.title,
        imageUrl: articleDetail.image || ''
      }
    }
    return {
      title: '展会详情'
    }
  }
})
